#pragma once
#include "Log.hpp"
#include <string>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

using namespace std;

const int size = 4096;
const string pathname = "/home/tr";
const int proj_id = 0x2345;

Log lg;

#define FIFO_FILE "./mypipe"
#define MODE 0664

enum 
{
    FIFO_CREATE_ERR = 1, 
    FIFO_DELETE_ERR,
    FIFO_OPEN_ERR
};

class Init
{
public:
    Init()
    {
        // 创建管道
        int n = mkfifo(FIFO_FILE, MODE);
        if (n == -1)
        {
            perror("mkfifo");
            exit(FIFO_CREATE_ERR);
        }
    }

    ~Init()
    {
        int m = unlink(FIFO_FILE);
        if (m == -1)
        {
            perror("unlink");
            exit(FIFO_DELETE_ERR);
        }
    }
};

void RemoveShm(int flag, key_t key)
{
    int shmid = shmget(key, size, flag);
    if (shmid < 0)
    {
        lg(Fatal, "get remove share memory error : %s", strerror(errno));
        exit(3);
    }

    shmctl(shmid, IPC_RMID, nullptr);
    lg(Debug, "remove success!");
}

key_t Getkey()
{
    key_t k = ftok(pathname.c_str(), proj_id);
    if (k < 0)
    {
        lg(Fatal, "ftok error : %s", strerror(errno));
        exit(1);
    }

    lg(Info, "ftok get cuccess! key : %d", k);
    return k;
}

int GetShareMemory(int flag)
{
    key_t k = Getkey();
    int shmid = shmget(k, size, flag);
    if (shmid < 0)
    {
        lg(Fatal, "creat share memory error : %s", strerror(errno));
        exit(2);
    }

    lg(Info, "creat share memory success! shmid : %d", shmid);
    return shmid;
}

// 根据不同的flag参数做不同的工作
int CreateShm()
{
    return GetShareMemory(IPC_CREAT | IPC_EXCL | 0666);
}

int GetShm()
{
    return GetShareMemory(IPC_CREAT);
}